import network from "../../../network/index";
export default {
  methods: {
    async loadData() {
      let {
        url,
        data,
        onError,
        formatBefore,
        formatAfter,
        resultKey,
        totalKey,
      } = this;
      // 无url的时候不执行请求
      if (!url) return;
      // 加载中标识符 清空选中
      this.loading = true;
      try {
        // 取出默认分页参数
        const { pageNum = 1, pageSize = 10, conditions = [] } = this;
        // 合并params，添加默认分页参数
        data = { ...data, pageSize, pageNum, conditions };
        // 格式化参数
        data = formatBefore(data);
        // 发起请求
        let res = await network.post({ url, data });
        // 格式化参数
        res = formatAfter(res);
        if (res.code === 200) {
          // 取出返回值中的数据、总条数
          let { [resultKey]: dataSource = [], [totalKey]: pageTotal = 0 } = res;
          // 保存数据源，分页参数
          this.dataSource = dataSource;
          this.pageTotal = pageTotal;
        }
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error(error);
        onError(error);
      }
    },
    refresh() {
      this.loadData();
    },
  },
};
